/*
 * Copyright (C) 2017-2021
 * All rights reserved, Designed By 深圳中科鑫智科技有限公司
 * Copyright authorization contact 18814114118
 */
package com.shop.cereshop.business.service.bsamecity.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kuaidi100.sdk.request.bsamecity.BsamecityOrderReq;
import com.kuaidi100.sdk.request.bsamecity.Goods;
import com.kuaidi100.sdk.response.bsamecity.BsamecityOrderResp;

import com.shop.cereshop.business.dao.bsamecity.BsamecityDeliveryTrackingDAO;
import com.shop.cereshop.business.dao.bsamecity.BsamecityOrderDAO;
import com.shop.cereshop.business.dao.buyer.CereBuyerReceiveDAO;
import com.shop.cereshop.business.dao.product.CereProductSkuDAO;
import com.shop.cereshop.business.dao.shop.CerePlatformShopDAO;
import com.shop.cereshop.business.service.bsamecity.BsamecityOrderService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.domain.bsamecity.BsamecityDeliveryTracking;
import com.shop.cereshop.commons.domain.bsamecity.BsamecityOrder;
import com.shop.cereshop.commons.domain.buyer.CereBuyerReceive;
import com.shop.cereshop.commons.domain.kuaidi.kd100.order.KdBsamecityOrderReq;
import com.shop.cereshop.commons.domain.kuaidi.kd100.order.resp.BsamecityOrderBaseResp;
import com.shop.cereshop.commons.domain.kuaidi.kd100.order.resp.baseCity.MyBsamecityPriceResp;
import com.shop.cereshop.commons.domain.kuaidi.kd100.order.resp.callBack.BasameCityOrderCallbackParam;
import com.shop.cereshop.commons.domain.product.CereProductSku;
import com.shop.cereshop.commons.domain.shop.CerePlatformShop;
import com.shop.cereshop.commons.result.Result;
import com.shop.cereshop.commons.utils.kd.baseCity.BaseCityKdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 业务实现类
 * 同城寄件订单表
 * </p>
 *
 * @author
 * @date 2025-08-11
 */
@Slf4j
@Service
public class BsamecityOrderServiceImpl implements BsamecityOrderService {

    //授权码
    @Value("${kd100.key}")
    private String key;

    //公司编号
    @Value("${kd100.secret}")
    private String secret;

    @Value("${kd100.order.callBackUrl}")
    private String callBackUrl;

    @Resource
    private BsamecityOrderDAO bsamecityOrderDAO;

    @Resource
    private BsamecityDeliveryTrackingDAO deliveryTrackingDAO;

    @Resource
    private CerePlatformShopDAO cerePlatformShopDAO;

    @Resource
    private CereBuyerReceiveDAO receiveDAO;
    @Resource
    private CereProductSkuDAO productSkuDAO;


    @Override
    public Result bsamecityPrice(KdBsamecityOrderReq bsamecityOrderReq) {
        CerePlatformShop cerePlatformShop = cerePlatformShopDAO.selectByPrimaryKey(bsamecityOrderReq.getShopId());
        if (BeanUtil.isEmpty(cerePlatformShop)) {
            return new Result<>("商家不存在");
        }
        CereBuyerReceive cereBuyerReceive = receiveDAO.selectByPrimaryKey(bsamecityOrderReq.getReceiveId());
        if (BeanUtil.isEmpty(cereBuyerReceive)) {
            return new Result<>("收货地址不存在");
        }
    //    List<CereProductSku> skuList = productSkuDAO.selectBySkuIdList(bsamecityOrderReq.getSkuIdList());
        List<CereProductSku> skuList =new ArrayList<>();
        if (CollUtil.isEmpty(skuList)) {
            return new Result<>("商品不存在");
        }
        String[] address = cereBuyerReceive.getReceiveAdress().split("-");
        if (address.length < 3) {
            return new Result<>("收货地址格式错误");
        }
        String[] locations = cereBuyerReceive.getLocation().split(",");
        if (locations.length < 2) {
            return new Result<>("收货地址经纬度错误");
        }
        BsamecityOrderReq request = new BsamecityOrderReq();
        request.setKuaidicom("shunfengtongcheng");
        request.setCallbackUrl(callBackUrl);
        request.setRecManName(cereBuyerReceive.getReceiveName());
        request.setRecManAddr(cereBuyerReceive.getReceiveName());
        request.setRecManMobile(cereBuyerReceive.getReceivePhone());
        request.setRecManProvince(address[0]);
        request.setRecManCity(address[1]);
        request.setRecManDistrict(address[2]);
        request.setRecManLng(locations[0]);
        request.setRecManLat(locations[1]);
        request.setRecManAddr(cereBuyerReceive.getReceiveAdress().replaceAll("-", "") + cereBuyerReceive.getAddress());
        String[] shopLocations = cerePlatformShop.getLocation().split(",");
        if (shopLocations.length < 2) {
            return new Result<>("发货地址经纬度错误");
        }
        request.setSendManLng(shopLocations[0]);
        request.setSendManLat(shopLocations[1]);
        request.setLbsType(2);
        request.setSendManName(cerePlatformShop.getChargePersonName());
        request.setSendManMobile(cerePlatformShop.getShopPhone());
        request.setSendManProvince(cerePlatformShop.getShopAdressProvince());
        request.setSendManCity(cerePlatformShop.getShopAdressCity());
        //获取商品集合中价格的总和
        request.setPrice(skuList.stream().map(CereProductSku::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add).toString());
        request.setSendManDistrict(cerePlatformShop.getShopAddressDist());
        request.setSendManAddr(cerePlatformShop.getShopAdressProvince() + cerePlatformShop.getShopAdressCity() + cerePlatformShop.getShopAddressDist() + cerePlatformShop.getShopAdressDetail());
        request.setWeight(skuList.stream().map(CereProductSku::getWeight).reduce(BigDecimal.ZERO, BigDecimal::add).toString());
        request.setRemark(bsamecityOrderReq.getRemark());
        request.setOrderType(bsamecityOrderReq.getOrderType());
        if (bsamecityOrderReq.getOrderType() == 2) {
            request.setExpectPickupTime(bsamecityOrderReq.getExpectFinishTime());
        }
        List<Goods> goodsList = new ArrayList<>();
        for (CereProductSku cereProductSku : skuList) {
            Goods goods = new Goods();
            goods.setName("狗粮");
            goods.setType("食品");
            goods.setCount(1);
            goodsList.add(goods);
        }
        request.setGoods(goodsList);
        BsamecityOrderBaseResp<MyBsamecityPriceResp> printBaseResp = BaseCityKdUtil.bsamecityPrice(key, secret, request);
//        BsamecityOrderBaseResp<BsamecityOrderResp> printBaseResp = BaseCityKdUtil.bsamecityOrder(key, secret, request);
        if (printBaseResp.getSuccess()) {
               /*     BsamecityOrderBaseResp<BsamecityOrderResp> printBaseResp = new BsamecityOrderBaseResp();
                    BsamecityOrderResp data = new BsamecityOrderResp();
                    data.setTaskId("DFE1F8BAB4784F8AA4E7563E7DDB6D62");
                    data.setOrderId("300191456");
                    data.setDeliveryDistance("7255");
                    data.setDeliverFee("45.85");
                    printBaseResp.setData(data);*/
//            saveOrder(bsamecityOrderReq.getOrderId(), request, printBaseResp.getData());
            return new Result<>(printBaseResp.getData(), CoReturnFormat.SUCCESS);
        }
        return new Result<>("下单失败");
    }

    private void saveOrder(String orderId, BsamecityOrderReq request, BsamecityOrderResp orderResp) {
        BsamecityOrder order = new BsamecityOrder();
        BeanUtil.copyProperties(request, order);
        order.setKdOrderId(orderResp.getOrderId());
        order.setGoodsJson(JSONObject.toJSONString(request.getGoods()));
        order.setOrderStatus(1);
        order.setOrderStage(1);
        order.setLocalOrderId(orderId);
        order.setTaskId(orderResp.getTaskId());
        order.setDeliveryDistance(orderResp.getDeliveryDistance());
        order.setDiscountFee(orderResp.getDiscountFee());
        order.setEstimateDeliveryTime(orderResp.getEstimateDeliveryTime());
        bsamecityOrderDAO.insert(order);
    }

    @Override
    public void saveOrderStatus(String taskId, BasameCityOrderCallbackParam param) {
        BsamecityDeliveryTracking deliveryTracking = new BsamecityDeliveryTracking();
        BeanUtil.copyProperties(param, deliveryTracking);
        List<BsamecityOrder> bsamecityOrder = bsamecityOrderDAO.selectList(new QueryWrapper<BsamecityOrder>().eq("task_id", taskId));
        if (CollUtil.isNotEmpty(bsamecityOrder)) {
            deliveryTracking.setLocalOrderId(bsamecityOrder.get(0).getLocalOrderId());
            bsamecityOrderDAO.updateByTaskId(taskId, param.getStatus());
        }
        deliveryTracking.setTaskId(taskId);
        deliveryTrackingDAO.insert(deliveryTracking);
    }
}
